package com.Endurancer.manager.service.impl;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import com.Endurancer.common.utils.DateUtils;
import com.Endurancer.manager.domain.BlogRelations;
import com.Endurancer.manager.domain.dto.BlogDto;
import com.Endurancer.manager.domain.dto.BlogItemDto;
import com.Endurancer.manager.domain.dto.SearchDto;
import com.Endurancer.manager.domain.vo.*;
import com.Endurancer.manager.mapper.BlogRelationsMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.Endurancer.manager.mapper.BlogPostMapper;
import com.Endurancer.manager.domain.BlogPost;
import com.Endurancer.manager.service.IBlogPostService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 博客详情信息Service业务层处理
 *
 * @author Endurancer
 * @date 2025-02-02
 */
@Service
public class BlogPostServiceImpl implements IBlogPostService
{
    @Autowired
    private BlogPostMapper blogPostMapper;
    @Autowired
    private BlogRelationsMapper blogRelationsMapper;

    /**
     * 查询博客详情信息
     *
     * @param postId 博客详情信息主键
     * @return 博客详情信息
     */
    @Override
    public BlogPost selectBlogPostByPostId(Long postId)
    {
        return blogPostMapper.selectBlogPostByPostId(postId);
    }

    /**
     * 查询博客详情信息列表
     *
     * @param blogPost 博客详情信息
     * @return 博客详情信息
     */
    @Override
    public List<BlogPost> selectBlogPostList(BlogPost blogPost)
    {
        return blogPostMapper.selectBlogPostList(blogPost);
    }

    /**
     * 新增博客详情信息
     *
     * @param blogPost 博客详情信息
     * @return 结果
     */
    @Override
    public int insertBlogPost(BlogPost blogPost)
    {
        blogPost.setCreateTime(DateUtils.getNowDate());
        return blogPostMapper.insertBlogPost(blogPost);
    }

    /**
     * 修改博客详情信息
     *
     * @param blogPost 博客详情信息
     * @return 结果
     */
    @Override
    public int updateBlogPost(BlogPost blogPost)
    {
        blogPost.setUpdateTime(DateUtils.getNowDate());
        return blogPostMapper.updateBlogPost(blogPost);
    }

    /**
     * 批量删除博客详情信息
     *
     * @param postIds 需要删除的博客详情信息主键
     * @return 结果
     */
    @Override
    public int deleteBlogPostByPostIds(Long[] postIds)
    {
        return blogPostMapper.deleteBlogPostByPostIds(postIds);
    }

    /**
     * 删除博客详情信息信息
     *
     * @param postId 博客详情信息主键
     * @return 结果
     */
    @Override
    public int deleteBlogPostByPostId(Long postId)
    {
        return blogPostMapper.deleteBlogPostByPostId(postId);
    }

    public List<Map<String, Object>> selectBlogArchives() {
        // 执行SQL查询，获取结果列表
        List<Map<String, Object>> results = blogPostMapper.selectBlogArchives();
        // 用于存储最终结果的列表
        List<Map<String, Object>> archives = new ArrayList<>();
        // 用于存储当前月份的事件
        Map<String, Object> currentMonth = null;
        List<Map<String, Object>> currentEvents = null; // 修改为Object以存储不同类型的值
        // 上一个处理的月份
        String lastMonth = null;
        for (Map<String, Object> result : results) {
            String month = (String) result.get("month");
            if (!month.equals(lastMonth)) {
                // 遇到新的月份，保存上一个月份的数据并初始化新月份
                if (currentMonth != null) {
                    currentMonth.put("events", currentEvents);
                    archives.add(currentMonth);
                }
                currentMonth = new HashMap<>();
                currentMonth.put("title", month);
                currentEvents = new ArrayList<>();
                lastMonth = month;
            }
            // 添加事件
            Map<String, Object> event = new HashMap<>(); // 修改为Object以存储不同类型的值
            event.put("date", (String) result.get("date"));
            event.put("title", (String) result.get("title"));
            event.put("postId", result.get("postId")); // 添加postId字段
            currentEvents.add(event);
        }

        // 添加最后一个月份的数据
        if (currentMonth != null) {
            currentMonth.put("events", currentEvents);
            archives.add(currentMonth);
        }

        return archives;
    }



    @Override
    public BlogDetailVo selectByPostId(Long postId) {
        return blogPostMapper.selectBlogDetailById(postId);
    }

    @Override
    public List<BlogTopVo> selectByTopBlog() {
        return blogPostMapper.selectByTopBlog();
    }

    @Override
    public List<BlogNewVo> selectByNewBlog() {
        return blogPostMapper.selectByNewBlog();
    }

    @Override
    public BlogTitleVo selectBlogTitle(Long postId) {
        return blogPostMapper.selectBlogTitle(postId);
    }

    @Override
    public BlogItemVo selectBlogItem(BlogItemDto blogItemDto) {
        // 先查询博客的点赞、收藏和评论数量
        BlogItemVo blogItemVo = blogPostMapper.selectBlogItem(blogItemDto.getPostId());
        if (blogItemDto.getUserId() != null) {
            // 如果用户 ID 不为 null，查询用户的交互信息
            BlogItemVo interactions = blogPostMapper.selectUserInteractions(blogItemDto.getPostId(), blogItemDto.getUserId());
            // 合并两个结果
            blogItemVo.setLike(interactions.isLike());
            blogItemVo.setCollection(interactions.isCollection());
            blogItemVo.setComment(interactions.isComment());
        }
        return blogItemVo;
    }

    @Transactional
    public Long selectBlogViewsCount(Long postId) {
        // 先从数据库查询当前博客文章
        BlogPost blogPost = blogPostMapper.selectBlogPostByPostId(postId);
        if (blogPost == null) {
            throw new RuntimeException("博客文章不存在");
        }
        // 增加浏览量
        blogPost.setViewsCount(blogPost.getViewsCount() == null? 1 : blogPost.getViewsCount() + 1);
        // 更新博客文章的浏览量
        blogPostMapper.updateBlogPost(blogPost);
        // 再次查询最新的浏览量
        BlogPost updatedBlog = blogPostMapper.selectBlogPostByPostId(postId);
        return updatedBlog.getViewsCount();
    }

    @Override
    public List<ArticleVo> selectByTagId(Long tagId) {
        return blogPostMapper.selectByTagId(tagId);
    }

    @Override
    public List<ArticleVo> selectByThemeId(Long themeId) {
        return blogPostMapper.selectByThemeId(themeId);
    }

    @Override
    public BlogCountVo selectBlogCount() {
         return blogPostMapper.selectBlogCount();
    }

    @Override
    public List<SearchVo> selectBlogByKeyWord(SearchDto searchDto) {
         return blogPostMapper.selectBlogByKeyWord(searchDto);
    }

    @Override
    public BlogPageVo selectPageByPostId(Long postId) {
        return blogPostMapper.selectPageByPostId(postId);
    }

    @Override
    public List<MyBlogVo> selectByUserId(Long userId) {
         return blogPostMapper.selectByUserId(userId);
    }

    @Override
    public List<MyBlogVo> selectCollect(Long userId) {
         return blogPostMapper.selectCollect(userId);
    }


    @Override
    public List<BlogVo> selectByTypeId(Long typeId) {
        return blogPostMapper.selectBlogByTypeId(typeId);
    }
   @Transactional
    public int addBlog(BlogDto blogDto) {
        BlogPost blogPost = new BlogPost();
        BeanUtil.copyProperties(blogDto, blogPost);
        blogPost.setCreateTime(new Date());
        // 博客文字计算
        Integer blogWord = calculateBlogWord(blogDto.getContent());
        blogPost.setBlogWord(blogWord);
        // 插入博客文章
        Long postId = blogPostMapper.addBlogPost(blogPost);
        // 插入标签关联表
        insertTagRelations(postId, blogDto.getTags());
        return 1;
    }

    @Transactional
    @Override
    public int updateBlog(BlogDto blogDto) {
        // 博客文字计算
        BlogPost blogPost = blogPostMapper.selectBlogPostByPostId(blogDto.getPostId());
        BeanUtils.copyProperties(blogDto, blogPost);
        // 博客文字计算
        Integer blogWord = calculateBlogWord(blogDto.getContent());
        blogPost.setBlogWord(blogWord);
        blogPost.setUpdateTime(new Date());
        // 更新博客文章
        int result = blogPostMapper.updateBlogPost(blogPost);
        // 删除旧的标签关联
        blogRelationsMapper.deleteRelationsByPostId(blogDto.getPostId());
        // 插入新的标签关联
        insertTagRelations(blogDto.getPostId(), blogDto.getTags());
        return result;
    }

    @Override
    public BlogDto selectMyBlog(Long postId) {
         return blogPostMapper.selectMyBlog(postId);
    }

    /**
     * 计算博客文字数量
     * @param content 博客内容
     * @return 文字数量
     */
    private int calculateBlogWord(String content) {
        if (content == null) {
            return 0;
        }
        // 简单的计算方式，去除空格后统计字符数量
        // 如果需要更精确地计算中文字数，可以在这里添加逻辑
        return content.replaceAll("\\s+", "").length();
    }
    /**
     * 插入博客文章与标签关联表
     * @param postId 博客文章ID
     * @param tagIds 标签ID列表
     */
    private void insertTagRelations(Long postId, List<Integer> tagIds) {
        if (tagIds != null && !tagIds.isEmpty()) {
            for (Integer tagId : tagIds) {
                BlogRelations relation = new BlogRelations();
                relation.setPostId(postId);
                relation.setTagId(tagId.longValue());
                blogRelationsMapper.insertBlogRelations(relation);
            }
        }
    }
}
